﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

#region

using System;
using System.Configuration;
using System.Globalization;
using System.IO;

#endregion

namespace Rio.WCF.Services.helpers
{
    public static class CacheManager
    {
        #region Constructors

        /// <summary>
        /// Initializes the <see cref="CacheManager"/> class.
        /// </summary>
        static CacheManager()
        {
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings.Get("UseCache")))
            {
                CacheEnabled = bool.Parse(ConfigurationManager.AppSettings.Get("UseCache"));
            }
            else
            {
                CacheEnabled = false;
            }

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings.Get("CacheDuration")))
            {
                CacheDuration = Convert.ToInt16(ConfigurationManager.AppSettings.Get("CacheDuration"));
            }
            else
            {
                CacheDuration = -1;
            }

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory")))
            {
                CacheDirectory = ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory");
            }
            else
            {
                CacheDirectory = Path.GetTempPath();
            }
        }

        #endregion

        #region Class Properties

        /// <summary>
        /// Gets the cache directory.
        /// </summary>
        public static string CacheDirectory { get; private set; }

        /// <summary>
        /// Gets the duration of the cache.
        /// </summary>
        /// <value>
        /// The duration of the cache.
        /// </value>
        public static int CacheDuration { get; private set; }

        /// <summary>
        /// Gets a value indicating whether [cache enabled].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [cache enabled]; otherwise, <c>false</c>.
        /// </value>
        public static bool CacheEnabled { get; private set; }

        #endregion

        #region Class Methods

        /// <summary>
        /// Cleans the cache directory.
        /// </summary>
        public static void CleanCacheDirectory()
        {
            if (!CacheEnabled)
                return;

            if (CacheDuration == -1)
                return;

            try
            {
                //Deletes all files witch older than the expected duration date 
                FileInfo[] files = new DirectoryInfo(CacheDirectory).GetFiles("*.*", SearchOption.AllDirectories);
                Array.ForEach(files, delegate(FileInfo file)
                                         {
                                             if (DateTime.Today <= file.CreationTime.Date.AddDays(CacheDuration))
                                             {
                                                 try
                                                 {
                                                     file.Delete();
                                                 }
                                                 catch
                                                 {
                                                 }
                                             }
                                         });

                //delete all empties folders
                DirectoryInfo[] directories = new DirectoryInfo(CacheDirectory).GetDirectories();
                Array.ForEach(directories, delegate(DirectoryInfo directory)
                                               {
                                                   if (directory.GetFileSystemInfos().Length == 0)
                                                   {
                                                       try
                                                       {
                                                           directory.Delete(true);
                                                       }
                                                       catch
                                                       {
                                                       }
                                                   }
                                               });
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError(
                    "------------- EXCEPTION IN WCF CleanCacheDirectory EXCEPTION[" + DateTime.Now + "] Message [" +
                    ex.Message + "]");
            }
        }

        /// <summary>
        /// Gets the user cache directory.
        /// </summary>
        /// <param name="p_bImport">if set to <c>true</c> [P_B import].</param>
        /// <param name="p_iUserId">The p_i user id.</param>
        /// <returns></returns>
        public static string GetUserCacheDirectory(bool p_bImport, long p_iUserId)
        {
            NetBay.Core.Log.LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            NetBay.Core.Log.LogManager.Instance().LogInfo("---------------------------Call of CreateCacheDirectory");

            string l_sTempDirectory;
            if (p_bImport)
            {
                l_sTempDirectory =
                    Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                                 p_iUserId.ToString(CultureInfo.InvariantCulture));
            }
            else
            {
                l_sTempDirectory = ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory");
            }
            Treatments.CheckDirectory(l_sTempDirectory);

            NetBay.Core.Log.LogManager.Instance().LogInfo(
                "---------------------------End of Call of CreateCacheDirectory");
            return l_sTempDirectory;
        }

        #endregion
    }
}